package com.xmtlxx.system.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.xmtlxx.common.constant.UserConstants;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.domain.entity.SysTenant;
import com.xmtlxx.common.core.domain.entity.SysUser;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.enums.UserType;
import com.xmtlxx.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmtlxx.system.domain.SysUserRole;
import com.xmtlxx.system.domain.vo.SysTenantVo;
import com.xmtlxx.system.mapper.SysTenantMapper;
import com.xmtlxx.system.mapper.SysUserMapper;
import com.xmtlxx.system.mapper.SysUserRoleMapper;
import com.xmtlxx.system.service.ISysDeptService;
import com.xmtlxx.system.service.ISysTenantService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 租户Service业务层处理
 *
 * @author xmtlxx
 * @date 2022-04-17
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysTenantServiceImpl implements ISysTenantService {

    private final SysTenantMapper baseMapper;

    private final SysUserMapper sysUserMapper;

    private final ISysDeptService sysDeptServic;

    private final SysUserRoleMapper userRoleMapper;

    /**
     * 查询租户
     *
     * @param tenantId 租户主键
     * @return 租户
     */
    @Override
    public SysTenant queryById(Long tenantId){
        return baseMapper.selectVoById(tenantId);
    }

    /**
     * 查询租户列表
     *
     * @param bo 租户
     * @return 租户
     */
    @Override
    public TableDataInfo<SysTenant> queryPageList(SysTenant bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysTenant> lqw = buildQueryWrapper(bo);
        Page<SysTenant> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询租户列表
     *
     * @param bo 租户
     * @return 租户
     */
    @Override
    public List<SysTenant> queryList(SysTenant bo) {
        LambdaQueryWrapper<SysTenant> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysTenant> buildQueryWrapper(SysTenant bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysTenant> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTenantId() != null, SysTenant::getTenantId, bo.getTenantId());
        lqw.like(StringUtils.isNotBlank(bo.getTenantName()), SysTenant::getTenantName, bo.getTenantName());
        lqw.eq(StringUtils.isNotBlank(bo.getLeader()), SysTenant::getLeader, bo.getLeader());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), SysTenant::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getEmail()), SysTenant::getEmail, bo.getEmail());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), SysTenant::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增租户
     *
     * @param vo 租户
     * @return 结果
     */
    @Override
    public Boolean insertByBo(SysTenantVo vo) {
        SysTenant add = new SysTenant();
        BeanUtil.copyProperties(vo,add);
        validEntityBeforeSave(add);

        boolean flag = baseMapper.insert(add) > 0;

        SysUser user = new SysUser();
        BeanUtil.copyProperties(vo,user);
        user.setPassword(BCrypt.hashpw(vo.getPassword()));
        user.setUserType(UserType.TENANT_ADMIN_USER.getUserType());
        user.setTenantId(add.getTenantId());
        sysUserMapper.insert(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return flag;
    }

    /**
     * 修改租户
     *
     * @param bo 租户
     * @return 结果
     */
    @Override
    public Boolean updateByBo(SysTenantVo bo) {
        SysTenant update = BeanUtil.toBean(bo,SysTenant.class);
        validEntityBeforeSave(update);
        SysUser user = sysUserMapper.getTenantAdminUser(update.getTenantId());
        user.setEmail(bo.getEmail());
        user.setStatus(bo.getStatus());
        user.setDeptId(bo.getDeptId());
        user.setRoleIds(bo.getRoleIds());
        user.setNickName(bo.getNickName());
        user.setPhonenumber(bo.getPhonenumber());
        user.setSex(bo.getSex());

        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId));
        // 新增用户与角色管理
        insertUserRole(user);

        sysUserMapper.updateById(user);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        Long[] roles = user.getRoleIds();
        if (ObjectUtil.isNotNull(roles)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.insertBatch(list);
            }
        }
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(SysTenant entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除租户
     *
     * @param ids 需要删除的租户主键
     * @return 结果
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    /**
     * 校验租户名称是否唯一
     *
     * @param tenantName 租户名称
     * @return 结果
     */
    @Override
    public String checkTenantNameUnique(String tenantName, Long tenantId) {
        long count = baseMapper.selectCount(new LambdaQueryWrapper<SysTenant>()
            .eq(SysTenant::getTenantName, tenantName)
            .eq(SysTenant::getDelFlag, "0")
            .ne(tenantId != null, SysTenant::getTenantId, tenantId));
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int updateStatus(SysTenant bo) {
        SysUser user = sysUserMapper.getTenantAdminUser(bo.getTenantId());
        user.setStatus(bo.getStatus());
        sysUserMapper.updateById(user);
        return baseMapper.updateById(bo);
    }

    /**
     * 取消授权用户角色
     *
     * @param user 用户和角色关联信息
     * @return 结果
     */
    @Override
    public int deleteAuthUser(SysUser user) {
        SysUser entity = sysUserMapper.selectUserById(user.getUserId());
        entity.setUserType("02");
        return sysUserMapper.updateById(entity);
    }

    /**
     * 批量取消授权用户租户
     *
     * @param tenantId 租户ID
     * @param userIds  需要取消授权的用户数据ID
     * @return 结果
     */
    @Override
    public int deleteAuthUsers(Long tenantId, Long[] userIds) {
        SysUser entity = new SysUser();
        entity.setUserType("02");
        return sysUserMapper.update(entity, new LambdaQueryWrapper<SysUser>()
            .eq(SysUser::getUserType, "01")
            .in(SysUser::getUserId, Arrays.asList(userIds)));
    }

    /**
     * 批量选择授权用户租户
     *
     * @param tenantId 租户ID
     * @param userIds  需要删除的用户数据ID
     * @return 结果
     */
    @Override
    public int insertAuthUsers(Long tenantId, Long[] userIds) {
        // 新增用户与租户管理
        SysUser entity = new SysUser();
        entity.setUserType("01");
        entity.setTenantId(tenantId);
        entity.setDeptId(sysDeptServic.getRootDeptByTenantId(tenantId).getDeptId());
        return sysUserMapper.update(entity, new LambdaQueryWrapper<SysUser>()
            .eq(SysUser::getUserType, "02")
            .in(SysUser::getUserId, Arrays.asList(userIds)));
    }
}
